import React, { useState, useEffect, useMemo, useCallback, lazy, Suspense } from 'react';
import { Card, Row, Col, Statistic, Button, message, Select, DatePicker, Space, Modal } from 'antd';
import { ReloadOutlined, SearchOutlined, DownloadOutlined } from '@ant-design/icons';
import * as signalR from '@microsoft/signalr';
import axios from 'axios';
import authService from './services/authService';
import { useDebounce } from './hooks/useDebounce';
import { useLocalStorage } from './hooks/useLocalStorage';
import LazyWrapper from './components/LazyWrapper';
import ResponsiveLayout from './components/ResponsiveLayout';
import MultiMetricChart from './components/MultiMetricChart';
import PerformanceDashboard from './components/PerformanceDashboard';
import EnhancedPerformanceDashboard from './components/EnhancedPerformanceDashboard';
import ExportDataPanel from './components/ExportDataPanel';
import AlertSystem from './components/AlertSystem';
import BatchOperationsPanel from './components/BatchOperationsPanel';
import { PerformanceMonitor } from './utils/performance';
import './App.css';

// 懒加载组件
const LazyLoginForm = lazy(() => import('./components/LoginForm'));
const LazyCityManagement = lazy(() => import('./components/CityManagement'));
const LazyDynamicWeatherDisplay = lazy(() => import('./components/DynamicWeatherDisplay'));
const LazyDynamicDataTable = lazy(() => import('./components/DynamicDataTable'));

const { RangePicker } = DatePicker;
const { Option } = Select;

interface DynamicWeatherData {
  id: string;
  cityId: string;
  cityName?: string;
  recordedAt: string;
  createdAt: string;
  [key: string]: any; // 动态指标数据
}

interface DynamicStatistics {
  id: string;
  cityId: string;
  statisticType: string;
  statisticDate: string;
  dataPointCount: number;
  createdAt: string;
  [key: string]: any; // 动态统计数据
}

interface City {
  id: string;
  name: string;
  country: string;
  latitude: number;
  longitude: number;
  isActive: boolean;
}

interface WeatherStats {
  totalCities: number;
  totalWeatherRecords: number;
  totalUsers: number;
  recentRecords: number;
  activeCities: number;
  lastDataCollection?: string;
  lastCollectionStatus: string;
}

function App() {
  const [selectedKey, setSelectedKey] = useLocalStorage('selectedMenuKey', '1');
  const [weatherData, setWeatherData] = useState<DynamicWeatherData[]>([]);
  const [realtimeData, setRealtimeData] = useState<DynamicWeatherData[]>([]);
  const [statisticsData, setStatisticsData] = useState<DynamicStatistics[]>([]);
  const [stats, setStats] = useState<WeatherStats | null>(null);
  const [connection, setConnection] = useState<signalR.HubConnection | null>(null);
  const [loading, setLoading] = useState(false);
  const [isAuthenticated, setIsAuthenticated] = useState(() => authService.isAuthenticated());
  const [exportModalVisible, setExportModalVisible] = useState(false);
  
  // 筛选相关状态
  const [cities, setCities] = useState<City[]>([]);
  const [selectedCityId, setSelectedCityId] = useLocalStorage<string | undefined>('selectedCityId', undefined);
  const [dateRange, setDateRange] = useState<[any, any] | null>(null);
  
  // 防抖处理的搜索参数
  const debouncedCityId = useDebounce(selectedCityId, 500);
  const debouncedDateRange = useDebounce(dateRange, 500);

  // 初始化性能监控和SignalR连接
  useEffect(() => {
    PerformanceMonitor.init();
    
    const newConnection = new signalR.HubConnectionBuilder()
      .withUrl('http://localhost:5197/weatherHub')
      .build();

    setConnection(newConnection);

    return () => {
      PerformanceMonitor.cleanup();
      if (newConnection) {
        newConnection.stop();
      }
    };
  }, []);

  // 启动SignalR连接
  useEffect(() => {
    if (connection) {
      connection.start()
        .then(() => {
          console.log('SignalR连接已建立');
          
          // 监听实时天气数据
          connection.on('ReceiveWeatherData', (data: DynamicWeatherData) => {
            console.log('收到实时天气数据:', data);
            setRealtimeData(prev => [data, ...prev.slice(0, 9)]); // 保持最新10条数据
            message.success(`收到新的天气数据: ${data.cityName || 'Unknown'}`);
          });
        })
        .catch(err => {
          console.error('SignalR连接失败:', err);
          message.error('实时数据连接失败');
        });
    }
  }, [connection]);

  // 获取城市列表（使用useCallback避免不必要的重新渲染）
  const fetchCities = useCallback(async () => {
    try {
      console.log('开始获取城市列表...');
      const response = await axios.get('http://localhost:5197/api/weather/cities');
      console.log('城市列表API响应:', response.data);
      setCities(response.data);
      console.log('城市列表设置成功，数量:', response.data?.length || 0);
    } catch (error: any) {
      console.error('获取城市列表失败:', error);
      console.error('错误详情:', {
        status: error.response?.status,
        statusText: error.response?.statusText,
        data: error.response?.data,
        message: error.message
      });
      message.error(`获取城市列表失败: ${error.response?.status || error.message}`);
    }
  }, []);

  // 获取历史天气数据（支持筛选，使用useCallback优化）
  const fetchWeatherData = useCallback(async (cityId?: string, startDate?: string, endDate?: string) => {
    setLoading(true);
    try {
      // 构建查询参数
      const params: any = {
        page: 1,
        pageSize: 100
      };
      
      if (cityId) {
        params.cityId = cityId;
      }
      
      if (startDate) {
        params.startDate = startDate;
      }
      
      if (endDate) {
        params.endDate = endDate;
      }
      
      const response = await axios.get('http://localhost:5197/api/weather', { params });
      // 后端返回的是PagedResult格式，需要提取data数组
      const responseData = response.data;
      if (responseData && Array.isArray(responseData.data)) {
        setWeatherData(responseData.data);
      } else if (Array.isArray(responseData)) {
        setWeatherData(responseData);
      } else {
        setWeatherData([]);
      }
      message.success('天气数据加载成功');
    } catch (error) {
      console.error('获取天气数据失败:', error);
      message.error('获取天气数据失败');
      setWeatherData([]); // 确保weatherData始终是数组
    } finally {
      setLoading(false);
    }
  }, []);

  // 获取统计数据（使用useCallback优化）
  const fetchStats = useCallback(async () => {
    try {
      const response = await axios.get('http://localhost:5197/api/statistics/overview');
      setStats(response.data);
    } catch (error) {
      console.error('获取统计数据失败:', error);
      message.error('获取统计数据失败');
    }
  }, []);

  // 获取动态统计数据（使用useCallback优化）
  const fetchStatistics = useCallback(async (cityId?: string, startDate?: string, endDate?: string) => {
    if (!cityId) return;
    
    try {
      let url = `http://localhost:5197/api/weather/statistics/range/${cityId}`;
      const params: any = {};
      
      if (startDate) params.startDate = startDate;
      if (endDate) params.endDate = endDate;
      
      const response = await axios.get(url, { params });
      setStatisticsData(response.data || []);
      message.success('统计数据加载成功');
    } catch (error) {
      console.error('获取统计数据失败:', error);
      message.error('获取统计数据失败');
      setStatisticsData([]);
    }
  }, []);

  // 模拟数据采集（使用useCallback优化）
  const simulateDataCollection = useCallback(async () => {
    try {
      const response = await axios.post('http://localhost:5197/api/weather/simulate', {
        baseTemperature: 20,
        count: 3
      });
      
      // 显示生成结果信息
      const result = response.data;
      message.success(`数据生成成功！为 ${result.cityCount} 个城市生成了 ${result.totalDataGenerated} 条天气数据`);
      
      // 自动刷新数据
      await fetchWeatherData();
      await fetchStats();
    } catch (error) {
      console.error('启动数据采集失败:', error);
      message.error('启动数据采集失败');
    }
  }, [fetchWeatherData, fetchStats]);

  // 登录成功处理（使用useCallback优化）
  const handleLoginSuccess = useCallback(() => {
    setIsAuthenticated(true);
    // 重新初始化数据
    fetchWeatherData();
    fetchStats();
  }, [fetchWeatherData, fetchStats]);

  // 登出处理（使用useCallback优化）
  const handleLogout = useCallback(() => {
    authService.logout();
    setIsAuthenticated(false);
    setWeatherData([]);
    setRealtimeData([]);
    setStats(null);
    if (connection) {
      connection.stop();
    }
    message.success('已退出登录');
  }, [connection]);

  // 初始化数据
  // 处理筛选查询（使用useCallback优化）
  const handleSearch = useCallback(() => {
    let startDate: string | undefined;
    let endDate: string | undefined;
    
    if (dateRange && dateRange[0] && dateRange[1]) {
      startDate = dateRange[0].format('YYYY-MM-DD');
      endDate = dateRange[1].format('YYYY-MM-DD');
    }
    
    fetchWeatherData(selectedCityId, startDate, endDate);
  }, [fetchWeatherData, selectedCityId, dateRange]);

  // 重置筛选条件（使用useCallback优化）
  const handleReset = useCallback(() => {
    setSelectedCityId(undefined);
    setDateRange(null);
    fetchWeatherData();
  }, [fetchWeatherData, setSelectedCityId]);

  useEffect(() => {
    if (isAuthenticated) {
      fetchWeatherData();
      fetchStats();
      fetchCities();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isAuthenticated]);

  // 准备图表数据（动态提取数值型指标，优化性能）
  const chartData = useMemo(() => {
    return weatherData.slice(0, 50).reverse().map(item => {
      const chartItem: any = {
        time: new Date(item.recordedAt).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
        cityName: item.cityName
      };
      
      // 动态添加数值型指标
      Object.entries(item).forEach(([key, value]) => {
        if (typeof value === 'number' && !['id', 'cityId'].includes(key)) {
          chartItem[key] = key === 'pressure' ? value / 10 : value; // 缩放气压数据
        }
      });
      
      return chartItem;
    });
  }, [weatherData]);

  // 防抖处理搜索效果
  useEffect(() => {
    if (debouncedCityId || debouncedDateRange) {
      let startDate: string | undefined;
      let endDate: string | undefined;
      
      if (debouncedDateRange && debouncedDateRange[0] && debouncedDateRange[1]) {
        startDate = debouncedDateRange[0].format('YYYY-MM-DD');
        endDate = debouncedDateRange[1].format('YYYY-MM-DD');
      }
      
      fetchWeatherData(debouncedCityId, startDate, endDate);
    }
  }, [debouncedCityId, debouncedDateRange, fetchWeatherData]);

  const renderContent = () => {
    switch (selectedKey) {
      case '1':
        return (
          <div>
            <Row gutter={16} style={{ marginBottom: 16 }}>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="城市总数"
                    value={stats?.totalCities || 0}
                    suffix="个"
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="天气记录总数"
                    value={stats?.totalWeatherRecords || 0}
                    suffix="条"
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="活跃城市"
                    value={stats?.activeCities || 0}
                    suffix="个"
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="近期记录"
                    value={stats?.recentRecords || 0}
                    suffix="条"
                  />
                </Card>
              </Col>
            </Row>
            
            <Card title="实时天气数据" style={{ marginBottom: 16 }}>
              {realtimeData.length > 0 ? (
                <Space direction="vertical" style={{ width: '100%' }}>
                  {realtimeData.slice(0, 3).map(item => (
                    <Suspense key={item.id} fallback={<LazyWrapper>加载中...</LazyWrapper>}>
                      <LazyDynamicWeatherDisplay data={item} compact />
                    </Suspense>
                  ))}
                </Space>
              ) : (
                <div style={{ textAlign: 'center', color: '#999', padding: 20 }}>
                  暂无实时数据
                </div>
              )}
            </Card>

            <MultiMetricChart 
              data={chartData} 
              title="多指标趋势分析"
              height={300}
              showCityFilter={false}
            />
            
            <EnhancedPerformanceDashboard />
          </div>
        );
      case '2':
        return (
          <Card 
            title="天气数据管理" 
            extra={
              <Button 
                type="primary" 
                icon={<ReloadOutlined />} 
                onClick={handleReset}
                loading={loading}
              >
                重置筛选
              </Button>
            }
          >
            {/* 筛选条件 */}
            <Card size="small" style={{ marginBottom: 16 }}>
              <Space wrap>
                <div>
                  <label style={{ marginRight: 8 }}>选择城市:</label>
                  <Select
                    placeholder="请选择城市"
                    style={{ width: 200 }}
                    value={selectedCityId}
                    onChange={setSelectedCityId}
                    allowClear
                  >
                    {cities.map(city => (
                      <Option key={city.id} value={city.id}>
                        {city.name} ({city.country})
                      </Option>
                    ))}
                  </Select>
                </div>
                <div>
                  <label style={{ marginRight: 8 }}>时间范围:</label>
                  <RangePicker
                    value={dateRange}
                    onChange={setDateRange}
                    format="YYYY-MM-DD"
                    placeholder={['开始日期', '结束日期']}
                  />
                </div>
                <Button 
                  type="primary" 
                  icon={<SearchOutlined />}
                  onClick={handleSearch}
                  loading={loading}
                >
                  查询
                </Button>
              </Space>
            </Card>
            
            <Suspense fallback={<LazyWrapper>加载数据表格...</LazyWrapper>}>
              <LazyDynamicDataTable
                data={weatherData}
                rowKey="id"
                pagination={{ pageSize: 10 }}
                loading={loading}
              />
            </Suspense>
          </Card>
        );
      case '3':
        return (
          <div>
            <Card title="数据统计" style={{ marginBottom: 16 }}>
              <Row gutter={16} style={{ marginBottom: 16 }}>
                <Col span={6}>
                  <Statistic
                    title="用户总数"
                    value={stats?.totalUsers || 0}
                    suffix="人"
                  />
                </Col>
                <Col span={6}>
                  <Statistic
                    title="最后采集状态"
                    value={stats?.lastCollectionStatus || '未知'}
                    valueStyle={{ color: stats?.lastCollectionStatus === '成功' ? '#3f8600' : '#cf1322' }}
                  />
                </Col>
                <Col span={6}>
                  <Statistic
                    title="最后采集时间"
                    value={stats?.lastDataCollection ? new Date(stats.lastDataCollection).toLocaleString() : '无'}
                  />
                </Col>
                <Col span={6}>
                  <Statistic
                    title="统计记录数"
                    value={statisticsData.length}
                    suffix="条"
                  />
                </Col>
              </Row>
              
              {/* 统计数据筛选 */}
              <Card size="small" style={{ marginBottom: 16 }}>
                <Space wrap>
                  <div>
                    <label style={{ marginRight: 8 }}>选择城市:</label>
                    <Select
                      placeholder="请选择城市"
                      style={{ width: 200 }}
                      value={selectedCityId}
                      onChange={(value) => {
                        setSelectedCityId(value);
                        if (value) {
                          const startDate = dateRange?.[0]?.format('YYYY-MM-DD');
                          const endDate = dateRange?.[1]?.format('YYYY-MM-DD');
                          fetchStatistics(value, startDate, endDate);
                        }
                      }}
                      allowClear
                    >
                      {cities.map(city => (
                        <Option key={city.id} value={city.id}>
                          {city.name} ({city.country})
                        </Option>
                      ))}
                    </Select>
                  </div>
                  <div>
                    <label style={{ marginRight: 8 }}>时间范围:</label>
                    <RangePicker
                      value={dateRange}
                      onChange={(dates) => {
                        setDateRange(dates);
                        if (selectedCityId && dates) {
                          fetchStatistics(selectedCityId, dates[0]?.format('YYYY-MM-DD'), dates[1]?.format('YYYY-MM-DD'));
                        }
                      }}
                      format="YYYY-MM-DD"
                      placeholder={['开始日期', '结束日期']}
                    />
                  </div>
                </Space>
              </Card>
            </Card>
            
            {/* 动态统计数据显示 */}
            {statisticsData.length > 0 && (
              <Card title="动态统计数据" style={{ marginBottom: 16 }}>
                <Suspense fallback={<LazyWrapper>加载统计表格...</LazyWrapper>}>
                  <LazyDynamicDataTable
                    data={statisticsData}
                    rowKey="id"
                    pagination={{ pageSize: 5 }}
                    size="small"
                  />
                </Suspense>
              </Card>
            )}
            
            <MultiMetricChart 
              data={chartData} 
              title="统计数据趋势分析"
              height={400}
              showCityFilter={true}
            />
          </div>
        );
      case '4':
        return (
          <Card title="系统设置">
            <div style={{ padding: '20px' }}>
              <Button 
                type="primary" 
                size="large"
                onClick={simulateDataCollection}
                style={{ marginRight: 16 }}
              >
                启动数据采集模拟
              </Button>
              <Button 
                size="large"
                onClick={fetchStats}
              >
                刷新统计数据
              </Button>
              <div style={{ marginTop: 20 }}>
                <p>系统状态: {connection?.state === 'Connected' ? '已连接' : '未连接'}</p>
                <p>实时数据: {realtimeData.length > 0 ? '正常接收' : '暂无数据'}</p>
              </div>
            </div>
          </Card>
        );
      case '5':
        return (
          <Suspense fallback={<LazyWrapper>加载城市管理...</LazyWrapper>}>
            <LazyCityManagement />
          </Suspense>
        );
      case '6':
        return <AlertSystem />;
      case '7':
        return <BatchOperationsPanel />;
      case '8':
        return <EnhancedPerformanceDashboard />;
      default:
        return <div>页面未找到</div>;
    }
  };

  // 如果未认证，显示登录界面
  if (!isAuthenticated) {
    return (
      <Suspense fallback={<LazyWrapper>加载登录界面...</LazyWrapper>}>
        <LazyLoginForm onLoginSuccess={handleLoginSuccess} />
      </Suspense>
    );
  }

  return (
    <>
      <ResponsiveLayout
        selectedKey={selectedKey}
        onMenuSelect={setSelectedKey}
        onLogout={handleLogout}
        username={authService.getUsername()}
        onExport={() => setExportModalVisible(true)}
      >
        {renderContent()}
      </ResponsiveLayout>

      <Modal
        title="数据导出"
        open={exportModalVisible}
        onCancel={() => setExportModalVisible(false)}
        footer={null}
        width={700}
      >
        <ExportDataPanel onClose={() => setExportModalVisible(false)} />
      </Modal>
    </>
  );
}

export default App;